var Currency = Currency || {};

Currency = (function(){
    return {
        init: function(){
          this.getCurrencyData();
          this.cacheElements();
          this.bindEvents();

        },
        cacheElements: function(){
            this.$exchange = $('#exchangeForm');
            this.$currency = this.$exchange.find('.currency');
            this.$currencyInput = this.$exchange.find('.currencyInput');
            this.$currencyBtn = this.$currency.find('.currencyList').find('button');
        },
        bindEvents: function(){
            this.$currencyInput.on('input', this.currencyCount);
            this.$currencyBtn.on('click', this.chooseCurrency);
        },
        chooseCurrency: function(e){
            var $this = $(this),
                $currencyBlock = $this.parents('.currency'),

                input = $currencyBlock.find('.currencyInput'),

                $currencyLabel = $currencyBlock.find('.currencyLabel');
            if($this.hasClass('active')){
                return false;
            }
            $this.parents('.currencyList').find('button').removeClass('active');
            $this.addClass('active');

            $currencyLabel.empty().text($this.data('currency'));


            Currency.currencyCount(e, $("#fromCurrency"));
        },
        currencyCount: function(e, currentCurrencyInput){
             var event = e || window.event,
                 $this = currentCurrencyInput || $(this),

                value = parseFloat($this.val()).toFixed(2),
                currentCurrencyBlock = $this.parents('.currency'),
                resultCurrencyBlock = currentCurrencyBlock.siblings('.currency'),
                currentRate = currentCurrencyBlock.find('.currencyList').find('button.active').data('currency-rate'),
                resultRate = resultCurrencyBlock.find('.currencyList').find('button.active').data('currency-rate'),
                resultInput = resultCurrencyBlock.find('.currencyInput'),

                resultValue = parseFloat(resultRate)/parseFloat(currentRate) * parseFloat(value);

            resultInput.val(resultValue.toFixed(2));
        },
        setRate: function(){
            Currency.$currencyBtn.each(function(){
                var currentCurrency = $(this).data('currency'),
                    rate = Currency.map[currentCurrency];
                $(this)
                    .attr('data-currency-rate', rate)
                    .data('currency-rate', rate);
            });
        },
        map:{},
        getCurrencyData: function(){
            $.get("/rate").done(function(result){
                Currency.map = $.extend(true, {}, JSON.parse(result));
                Currency.setRate();
                Currency.currencyCount(null, $('#fromCurrency'));
            });
        }
    };
})();

$(function(){
    Currency.init();
});

